<template>
  <div>
    <!-- 查询表单 -->
    <div class="check-form-box">
      <el-form
        :inline="true"
        :model="searchModel.data"
        class="demo-form-inline"
      >
        <el-form-item label="姓名">
          <el-input
            v-model.trim="searchModel.username"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input
            v-model.trim="searchModel.mobile"
            placeholder="请输入手机号码"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchModel.state" placeholder="请选择状态">
            <el-option label="全部" :value="null" />
            <el-option label="禁用" value="0" />
            <el-option label="启用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" color="#ea5b24" @click="searchUser()"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            color="#ea5b24"
            @click="showDialog(0, null)"
            v-if="pinia.isShow[39]"
            >添加</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <!-- 列表 -->
    <div>
      <el-table :data="tableData.data" style="width: 100%">
        <el-table-column width="80" sortable prop="id" label="ID" />
        <el-table-column prop="gmtCreate" label="注册时间" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="mobile" label="手机号码" />
        <el-table-column prop="roles" label="所属角色">
          <template v-slot:default="scope">
            {{ scope.row.roles != null ? roleName(scope.row.roles) : "" }}
          </template>
        </el-table-column>

        <el-table-column prop="desp" label="备注" />
        <el-table-column prop="state" :formatter="judgeState" label="状态" />
        <el-table-column fixed="right" label="操作" width="120">
          <template v-slot:default="scope">
            <div class="div-cell">
              <el-button
                link
                type="primary"
                size="small"
                @click="showDialog(1, scope.row)"
                v-if="pinia.isShow[41]"
                >编辑</el-button
              >
              <el-button
                link
                type="primary"
                size="small"
                @click="disableAdmin(scope.row)"
                v-if="pinia.isShow[40]"
                >{{ scope.row.state == 1 ? "禁用" : "启用" }}</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <div style="text-align: center">
        <el-pagination
          :total="totalNum"
          @current-change="handleCurrentChange"
          background
          :page-size="size"
          layout="prev, pager, next, total"
          :current-page="page"
        />
      </div>
    </div>

    <!--添加/编辑管理员表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      center="true"
      modal="true"
      width="25%"
    >
      <el-form :model="adminModel" :rules="rules" ref="ruleFormRef">
        <el-form-item label="id" :label-width="0" hidden="true">
          <el-input v-model.trim="adminModel.id" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="姓名"
          :label-width="editFormLabelWidth"
          prop="username"
        >
          <el-input v-model.trim="adminModel.username" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="手机号码"
          :label-width="editFormLabelWidth"
          prop="mobile"
        >
          <el-input
            v-model.trim="adminModel.mobile"
            maxlength="11"
            autocomplete="off"
            :formatter="(value) => value.replace(/[^\d]/g, '')"
          />
        </el-form-item>
        <el-form-item
          label="角色"
          :label-width="editFormLabelWidth"
          prop="roleIds"
        >
          <el-select
            v-model="adminModel.roleIds"
            multiple
            placeholder="请选择角色"
            class="select-roles"
          >
            <el-option
              v-for="item in roles.data"
              :value="item['value']"
              :label="item['label']"
              :key="item['value']"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="dialogType == 0"
          label="初始密码"
          prop="secret"
          :label-width="editFormLabelWidth"
        >
          <el-input v-model.trim="adminModel.secret" autocomplete="off" />
        </el-form-item>
        <el-form-item label="备注" :label-width="editFormLabelWidth">
          <el-input v-model.trim="adminModel.desp" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="formSubmit(ruleFormRef)"
            color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  findEmployeeApi,
  addEmployeeApi,
  updateEmployeeApi,
  roleFindApi,
} from "../../../api/index";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive([]);
const totalNum = ref(0);
const page = ref(1);
const size = 8;

// 控制对话框
const dialogVisible = ref(false);
const dialogTitle = ref("");
const dialogType = ref(0);
const editFormLabelWidth = "80px";
// 搜索模型
const searchModel: any = reactive({
  username: null,
  state: null,
  mobile: null,
  // roles: null,
  page: page,
  size: size,
});
// 添加/编辑模型
const adminModel = reactive({
  id: null,
  username: null,
  nickname: null,
  secret: null,
  mobile: null,
  desp: null,
  state: null,
  roleIds: [],
});

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  secret: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "密码只能由数字与字母组合,不包含特殊字符",
      trigger: "blur",
    },
    // { pattern: /(?=.*\d)(?=.*[a-zA-Z])/, message: "密码必须由数字与字母组合,不包含特殊字符", trigger: 'blur' },
    { min: 6, max: 10, message: "密码只允许为6~10位", trigger: "blur" },
  ],
  roleIds: [{ required: true, message: "请选择角色", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "手机号只能为11位", trigger: "blur" },
  ],
  username: [{ required: true, message: "请输入员工姓名", trigger: "blur" }],
});

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  searchEmployee(flipData);
};

// 控制添加/编辑dialog显示
const showDialog = (type: number, row) => {
  dialogVisible.value = true;
  dialogType.value = type;
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
  if (type === 0) {
    //添加管理员
    dialogTitle.value = "添加管理员";
    findAllRoles();
    Object.keys(adminModel).forEach((key) => (adminModel[key] = ""));
  } else {
    //编辑管理员
    dialogTitle.value = "编辑管理员";
    findAllRoles();
    adminModel.id = row.id;
    adminModel.username = row.username;
    adminModel.mobile = row.mobile;
    adminModel.roleIds = [];
    if (row.roles) {
      row.roles.forEach((val) => {
        adminModel.roleIds.push(val.id);
      });
    }
    adminModel.desp = row.desp;
  }
};

/**
 * 添加/编辑
 */
const formSubmit = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (dialogType.value === 0) {
        addEmployeeApi(adminModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "添加成功.",
              type: "success",
            });
            searchEmployee(searchModel);
          } else {
            switch (res.data.code) {
              case 6000:
                ElMessage.error("添加失败:员工姓名已存在");
                break;
              default:
                ElMessage.error("添加失败.");
                break;
            }
          }
        });
      } else {
        adminModel.state = null;
        updateEmployeeApi(adminModel).then((res) => {
          if (res.data.code === 2000) {
            ElMessage({
              message: "编辑成功.",
              type: "success",
            });
            searchEmployee(searchModel);
          } else {
            ElMessage.error("编辑失败");
          }
        });
      }
      Object.keys(adminModel).forEach((key) => (adminModel[key] = ""));
      dialogVisible.value = false;
    } else {
      return false;
    }
  });
};

// 搜索提现订单
const searchUser = () => {
  page.value = 1;
  searchParmSearch();
  searchEmployee(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (!searchModel[key]) {
      searchModel[key] = null;
    }
  });
};

//条件查询角色列表
const searchEmployee = (searchModel) => {
  findEmployeeApi(searchModel).then((res) => {
    if (res.data.code === 2000) {
      tableData.data = res.data.data.data;
      totalNum.value = res.data.data.total;
    } else {
      ElMessage.error("查询失败");
    }
  });
};

// 启/禁用管理员
const disableAdmin = (row) => {
  ElMessageBox.confirm(
    `是否确认${row.state == 1 ? "禁用" : "启用"}该员工?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    updateEmployeeApi({
      id: row.id,
      state: row.state == 1 ? "0" : "1",
    }).then((res) => {
      if (res.data.code === 2000) {
        row.state = row.state == 1 ? "0" : "1";
        ElMessage({
          message: "成功.",
          type: "success",
        });
      } else {
        ElMessage.error("失败");
      }
    });
  });
};

// 判断代理状态显示
const judgeState = (row, col) => {
  if (row.state == 1) {
    return "启用";
  } else {
    return "禁用";
  }
};

// 处理所属角色显示
const roleName = (roles) => {
  let str = "";
  roles.filter((x) => (str += x.roleName + " "));
  return str;
};

// 查询所有的角色
let roles: any = reactive([]);
const findAllRoles = () => {
  roleFindApi({}).then((res) => {
    if (res.data.code === 2000) {
      let dataList = res.data.data.data;
      const roleData = dataList.filter((item) => {
        return item.state == 1;
      });
      roles.data = Array.from(roleData).map((item, idx) => ({
        value: item["id"],
        label: item["roleName"],
      }));
    } else {
      ElMessage.error("查询角色失败");
    }
  });
};

onMounted(() => {
  searchEmployee(searchModel);
});
</script>

<style>
.select-roles {
  width: 100%;
}
</style>
